const httpStatus = require('http-status');
const { Food, FoodCategory } = require('../models');
const ApiError = require('../utils/ApiError');
const mongoose = require('mongoose');
const logger = require('../utils/logger');

/**
 * 获取食物列表
 * @param {Object} filter - 过滤条件
 * @param {Object} options - 查询选项
 * @returns {Promise<{foods: Array, page: number, limit: number, total: number}>}
 */
const getFoods = async (filter, options) => {
  // 检查是否请求所有数据
  const getAllData = options.all === 'true' || options.all === true;
  
  // 如果请求所有数据，则不使用分页
  const limit = getAllData ? 0 : (options.limit && parseInt(options.limit, 10) > 0 ? parseInt(options.limit, 10) : 20);
  const page = getAllData ? 1 : (options.page && parseInt(options.page, 10) > 0 ? parseInt(options.page, 10) : 1);
  const skip = getAllData ? 0 : (page - 1) * limit;

  // 构建排序
  const sortField = options.sortBy || 'name';
  const sortOrder = options.sortOrder === 'desc' ? -1 : 1;
  const sort = { [sortField]: sortOrder };

  // 默认排除已删除食物
  if (filter.isDeleted === undefined) {
    filter.isDeleted = false;
  }
  
  // 处理分类ID转为ObjectId
  if (filter.categoryId) {
    try {
      filter.categoryId = new mongoose.Types.ObjectId(filter.categoryId);
    } catch (error) {
      console.error('分类ID格式无效:', filter.categoryId);
      throw new ApiError(httpStatus.BAD_REQUEST, '无效的分类ID');
    }
  }

  // 获取总数和食物列表
  const countPromise = Food.countDocuments(filter).exec();
  // 构建查询
  let query = Food.find(filter).sort(sort);
  
  // 只有在不请求所有数据时才应用分页
  if (!getAllData) {
    query = query.skip(skip).limit(limit);
  }
  
  // 优化：使用lean()提高查询性能，返回纯JavaScript对象而不是Mongoose文档
  const foodsPromise = query.lean().exec();

  const [total, foods] = await Promise.all([countPromise, foodsPromise]);

  // 获取分类信息
  const categoryIds = [...new Set(foods.map(food => food.categoryId).filter(id => id))];
  let categories = [];
  
  // 打印分类ID进行调试
  console.log('找到的分类IDs:', categoryIds.map(id => id.toString()));
  
  if (categoryIds.length > 0) {
    categories = await FoodCategory.find({
      _id: { $in: categoryIds },
      isDeleted: false
    }).lean().exec(); // 使用lean()提高性能
    
    console.log('查询到的分类数量:', categories.length);
  }

  // 构建分类Map，便于查找
  const categoryMap = {};
  categories.forEach(category => {
    categoryMap[category._id.toString()] = {
      _id: category._id,
      name: category.name
    };
  });

  // 构建响应数据
  const formattedFoods = foods.map(food => {
    const nutrition = food.nutrition || {};
    // 安全地处理categoryId，确保它存在才调用toString
    let categoryIdStr = null;
    let category = { _id: null, name: '未知分类' };
    
    if (food.categoryId) {
      categoryIdStr = food.categoryId.toString();
      if (categoryMap[categoryIdStr]) {
        category = categoryMap[categoryIdStr];
        console.log(`食物 ${food.name} 关联到分类: ${category.name}`);
      } else {
        console.log(`食物 ${food.name} 的分类ID ${categoryIdStr} 在分类集合中未找到`);
      }
    } else {
      console.log(`食物 ${food.name} 没有分类ID`);
    }
    
    return {
      _id: food._id,
      name: food.name,
      category,
      image: food.image || '',
      unit: food.unit || '克',
      calories: food.calories || 0,
      nutrition: {
        protein: nutrition.protein || 0,
        fat: nutrition.fat || 0,
        carbohydrate: nutrition.carbohydrate || 0,
        fiber: nutrition.fiber || 0,
        sugar: nutrition.sugar || 0,
        sodium: nutrition.sodium || 0,
        cholesterol: nutrition.cholesterol || 0,
        vitamins: nutrition.vitamins || {},
        minerals: nutrition.minerals || {}
      },
      isVerified: food.isVerified,
      source: food.source || '',
      createdAt: food.createdAt,
      updatedAt: food.updatedAt
    };
  });

  return {
    foods: formattedFoods,
    page,
    limit: getAllData ? formattedFoods.length : limit,
    total
  };
};

/**
 * 获取全部食物列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Array>} 食物列表
 */
const getAllFoods = async (options) => {
  // 构建排序
  const sortField = options.sortBy || 'name';
  const sortOrder = options.sortOrder === 'desc' ? -1 : 1;
  const sort = { [sortField]: sortOrder };

  // 设置基本过滤条件，只获取未删除的食物
  const filter = { isDeleted: false };
  
  try {
    // 获取全部食物
    const foods = await Food.find(filter)
      .sort(sort)
      .lean()
      .exec();
    
    console.log(`获取到${foods.length}条食物数据`);
    
    // 获取所有分类ID
    const categoryIds = [...new Set(foods.map(food => food.categoryId).filter(id => id))];
    let categories = [];
    
    console.log('找到的分类IDs:', categoryIds.map(id => id.toString()));
    
    // 获取所有相关分类
    if (categoryIds.length > 0) {
      categories = await FoodCategory.find({
        _id: { $in: categoryIds },
        isDeleted: false
      }).lean().exec();
      
      console.log('查询到的分类数量:', categories.length);
      
      // 如果分类数量与分类ID数量不匹配，记录差异
      if (categories.length !== categoryIds.length) {
        const foundIds = categories.map(c => c._id.toString());
        const missingIds = categoryIds
          .map(id => id.toString())
          .filter(id => !foundIds.includes(id));
        
        console.log('未找到的分类IDs:', missingIds);
        
        // 检查这些分类是否存在但已被标记为删除
        if (missingIds.length > 0) {
          const deletedCategories = await FoodCategory.find({
            _id: { $in: missingIds.map(id => new mongoose.Types.ObjectId(id)) },
            isDeleted: true
          }).lean().exec();
          
          console.log('已删除的分类数量:', deletedCategories.length);
          
          // 将这些已删除的分类添加到结果中，但标记它们
          deletedCategories.forEach(cat => {
            categories.push({
              ...cat,
              name: `${cat.name} (已删除)`
            });
          });
        }
      }
    }

    // 构建分类Map，便于查找
    const categoryMap = {};
    categories.forEach(category => {
      categoryMap[category._id.toString()] = {
        _id: category._id,
        name: category.name
      };
    });

    // 格式化食物数据
    const formattedFoods = foods.map(food => {
      const nutrition = food.nutrition || {};
      let categoryIdStr = null;
      let category = { _id: null, name: '未知分类' };
      
      if (food.categoryId) {
        categoryIdStr = food.categoryId.toString();
        if (categoryMap[categoryIdStr]) {
          category = categoryMap[categoryIdStr];
        } else {
          console.log(`食物 ${food.name} 的分类ID ${categoryIdStr} 在分类集合中未找到`);
        }
      }
      
      return {
        _id: food._id,
        name: food.name,
        category,
        image: food.image || '',
        unit: food.unit || '克',
        calories: food.calories || 0,
        nutrition: {
          protein: nutrition.protein || 0,
          fat: nutrition.fat || 0,
          carbohydrate: nutrition.carbohydrate || 0,
          fiber: nutrition.fiber || 0,
          sugar: nutrition.sugar || 0,
          sodium: nutrition.sodium || 0,
          cholesterol: nutrition.cholesterol || 0,
          vitamins: nutrition.vitamins || {},
          minerals: nutrition.minerals || {}
        },
        isVerified: food.isVerified,
        source: food.source || '',
        createdAt: food.createdAt,
        updatedAt: food.updatedAt
      };
    });

    return {
      foods: formattedFoods,
      total: formattedFoods.length
    };
  } catch (error) {
    console.error('获取全部食物列表失败:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, '获取全部食物列表失败');
  }
};

/**
 * 根据ID获取食物详情
 * @param {string} id - 食物ID
 * @returns {Promise<Food>}
 */
const getFoodById = async (id) => {
  console.log(`[getFoodById] Received id: '${id}', type: ${typeof id}`);
  // 详细检查ID字符串
  console.log(`[getFoodById] ID string length: ${id.length}`);
  for (let i = 0; i < id.length; i++) {
    console.log(`[getFoodById] Char at ${i}: '${id[i]}', ASCII: ${id.charCodeAt(i)}`);
  }

  let foodId;
  try {
    // 尝试硬编码转换，用于调试
    try {
      const testObjectId = new mongoose.Types.ObjectId('681816cedd02bf9dbea85b19');
      console.log(`[getFoodById] Hardcoded ID test conversion successful: ${testObjectId}`);
    } catch (testError) {
      console.error(`[getFoodById] Hardcoded ID test conversion FAILED: ${testError.message}`);
    }

    foodId = new mongoose.Types.ObjectId(id);
  } catch (error) {
    console.error(`[getFoodById] Conversion error for id '${id}': ${error.message}`);
    throw new ApiError(httpStatus.BAD_REQUEST, '无效的食物ID格式');
  }
  
  const food = await Food.findOne({ _id: foodId, isDeleted: false });
  if (!food) {
    throw new ApiError(httpStatus.NOT_FOUND, '食物不存在');
  }
  
  // 获取分类信息
  let category = { _id: null, name: '未知分类' };
  
  if (food.categoryId) {
    try {
      const foundCategory = await FoodCategory.findOne({ 
        _id: food.categoryId, 
        isDeleted: false 
      });
      
      if (foundCategory) {
        category = {
          _id: foundCategory._id,
          name: foundCategory.name
        };
        console.log(`食物 ${food.name} 关联到分类: ${category.name}`);
      } else {
        console.log(`食物 ${food.name} 的分类ID ${food.categoryId} 在分类集合中未找到`);
        
        // 检查分类是否存在但已被删除
        const deletedCategory = await FoodCategory.findOne({
          _id: food.categoryId,
          isDeleted: true
        });
        
        if (deletedCategory) {
          console.log(`食物 ${food.name} 关联的分类已被删除: ${deletedCategory.name}`);
          category = {
            _id: deletedCategory._id,
            name: `${deletedCategory.name} (已删除)`
          };
        }
      }
    } catch (error) {
      console.error(`获取食物 ${food.name} 的分类信息失败:`, error);
    }
  } else {
    console.log(`食物 ${food.name} 没有分类ID`);
  }

  const nutrition = food.nutrition || {};
  
  // 格式化返回数据
  return {
    _id: food._id,
    name: food.name,
    category,
    image: food.image || '',
    unit: food.unit,
    calories: food.calories,
    nutrition: {
      protein: nutrition.protein || 0,
      fat: nutrition.fat || 0,
      carbohydrate: nutrition.carbohydrate || 0,
      fiber: nutrition.fiber || 0,
      sugar: nutrition.sugar || 0,
      sodium: nutrition.sodium || 0,
      cholesterol: nutrition.cholesterol || 0,
      vitamins: nutrition.vitamins || {},
      minerals: nutrition.minerals || {}
    },
    isVerified: food.isVerified,
    source: food.source || '',
    createdAt: food.createdAt,
    updatedAt: food.updatedAt
  };
};

/**
 * 搜索和筛选食物
 * @param {Object} filter - 筛选条件
 * @param {Object} options - 查询选项
 * @returns {Promise<{foods: Array, page: number, limit: number, total: number, totalPages: number}>}
 */
const searchFoods = async (filter, options) => {
  try {
    // 默认排除已删除食物
    if (filter.isDeleted === undefined) {
      filter.isDeleted = false;
    }
    
    // 处理分类ID转为ObjectId
    if (filter.categoryId) {
      try {
        filter.categoryId = new mongoose.Types.ObjectId(filter.categoryId);
      } catch (error) {
        console.error('分类ID格式无效:', filter.categoryId);
        throw new ApiError(httpStatus.BAD_REQUEST, '无效的分类ID');
      }
    }
    
    console.log('搜索食物过滤条件:', JSON.stringify(filter, null, 2));
    
    // 分页设置
    const page = options.page || 1;
    const limit = options.limit || 20;
    const skip = (page - 1) * limit;
    
    // 排序设置
    const sortField = options.sortBy || 'name';
    const sortOrder = options.sortOrder === 'desc' ? -1 : 1;
    const sort = { [sortField]: sortOrder };
    
    // 获取总数和食物列表
    const countPromise = Food.countDocuments(filter).exec();
    const foodsPromise = Food.find(filter)
      .sort(sort)
      .skip(skip)
      .limit(limit)
      .lean()
      .exec();
    
    const [total, foods] = await Promise.all([countPromise, foodsPromise]);
    const totalPages = Math.ceil(total / limit);
    
    console.log(`搜索到${foods.length}条食物数据，总计${total}条`);
    
    // 获取分类信息
    const categoryIds = [...new Set(foods.map(food => food.categoryId).filter(id => id))];
    let categories = [];
    
    console.log('找到的分类IDs:', categoryIds.map(id => id.toString()));
    
    if (categoryIds.length > 0) {
      categories = await FoodCategory.find({
        _id: { $in: categoryIds },
        isDeleted: false
      }).lean().exec();
      
      console.log('查询到的分类数量:', categories.length);
      
      // 如果分类数量与分类ID数量不匹配，记录差异并检查已删除的分类
      if (categories.length !== categoryIds.length) {
        const foundIds = categories.map(c => c._id.toString());
        const missingIds = categoryIds
          .map(id => id.toString())
          .filter(id => !foundIds.includes(id));
        
        console.log('未找到的分类IDs:', missingIds);
        
        // 检查这些分类是否存在但已被标记为删除
        if (missingIds.length > 0) {
          const deletedCategories = await FoodCategory.find({
            _id: { $in: missingIds.map(id => new mongoose.Types.ObjectId(id)) },
            isDeleted: true
          }).lean().exec();
          
          console.log('已删除的分类数量:', deletedCategories.length);
          
          // 将这些已删除的分类添加到结果中，但标记它们
          deletedCategories.forEach(cat => {
            categories.push({
              ...cat,
              name: `${cat.name} (已删除)`
            });
          });
        }
      }
    }
    
    // 构建分类Map，便于查找
    const categoryMap = {};
    categories.forEach(category => {
      categoryMap[category._id.toString()] = {
        _id: category._id,
        name: category.name
      };
    });
    
    // 构建响应数据
    const formattedFoods = foods.map(food => {
      const nutrition = food.nutrition || {};
      let categoryIdStr = null;
      let category = { _id: null, name: '未知分类' };
      
      if (food.categoryId) {
        categoryIdStr = food.categoryId.toString();
        if (categoryMap[categoryIdStr]) {
          category = categoryMap[categoryIdStr];
        } else {
          console.log(`食物 ${food.name} 的分类ID ${categoryIdStr} 在分类集合中未找到`);
        }
      } else {
        console.log(`食物 ${food.name} 没有分类ID`);
      }
      
      return {
        _id: food._id,
        name: food.name,
        category,
        image: food.image || '',
        unit: food.unit || '克',
        calories: food.calories || 0,
        nutrition: {
          protein: nutrition.protein || 0,
          fat: nutrition.fat || 0,
          carbohydrate: nutrition.carbohydrate || 0,
          fiber: nutrition.fiber || 0,
          sugar: nutrition.sugar || 0,
          sodium: nutrition.sodium || 0,
          cholesterol: nutrition.cholesterol || 0,
          vitamins: nutrition.vitamins || {},
          minerals: nutrition.minerals || {}
        },
        isVerified: food.isVerified,
        source: food.source || '',
        createdAt: food.createdAt,
        updatedAt: food.updatedAt
      };
    });
    
    return {
      foods: formattedFoods,
      page,
      limit,
      total,
      totalPages
    };
  } catch (error) {
    console.error('搜索食物失败:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, error.message || '搜索食物失败');
  }
};

/**
 * 创建或更新食物分类
 * 如果数据库中不存在该分类，则创建新分类
 * @param {string} categoryName - 分类名称
 * @returns {Promise<Object>} 分类对象
 */
const getOrCreateFoodCategory = async (categoryName) => {
  try {
    if (!categoryName || typeof categoryName !== 'string') {
      console.log('创建分类时没有提供有效的分类名称');
      throw new ApiError(httpStatus.BAD_REQUEST, '分类名称不能为空');
    }
    
    // 查找匹配的分类
    let category = await FoodCategory.findOne({ 
      name: categoryName, 
      isDeleted: false 
    });
    
    // 如果找到了匹配的分类，直接返回
    if (category) {
      console.log(`找到已存在的分类: ${categoryName}`);
      return {
        _id: category._id,
        name: category.name
      };
    }
    
    // 创建新分类
    console.log(`创建新分类: ${categoryName}`);
    const newCategory = await FoodCategory.create({
      name: categoryName,
      description: `${categoryName}类食物`,
    });
    
    return {
      _id: newCategory._id,
      name: newCategory.name
    };
  } catch (error) {
    console.error('创建食物分类失败:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, '创建食物分类失败');
  }
};

/**
 * 创建新的食物
 * @param {Object} foodData - 食物数据
 * @returns {Promise<Object>} 创建的食物对象
 */
const createFood = async (foodData) => {
  try {
    logger.info(`正在创建新的食物: ${foodData.name}`);
    
    // 验证分类ID是否存在
    const categoryExists = await FoodCategory.exists({ _id: new mongoose.Types.ObjectId(foodData.categoryId) });
    if (!categoryExists) {
      logger.error(`创建食物失败: 分类ID ${foodData.categoryId} 不存在`);
      throw new Error('分类ID不存在');
    }
    
    // 创建新的食物文档
    const food = new Food({
      name: foodData.name,
      categoryId: new mongoose.Types.ObjectId(foodData.categoryId),
      image: foodData.image || '',
      unit: foodData.unit || '克',
      calories: foodData.calories,
      nutrition: {
        protein: foodData.nutrition.protein,
        fat: foodData.nutrition.fat,
        carbohydrate: foodData.nutrition.carbohydrate,
        fiber: foodData.nutrition.fiber || 0,
        sugar: foodData.nutrition.sugar || 0,
        sodium: foodData.nutrition.sodium || 0,
        cholesterol: foodData.nutrition.cholesterol || 0
      },
      isVerified: foodData.isVerified || false,
      source: foodData.source || '',
      isDeleted: false
    });
    
    // 保存食物到数据库
    const savedFood = await food.save();
    logger.info(`食物创建成功: ${savedFood.name}, ID: ${savedFood._id}`);
    
    return savedFood;
  } catch (error) {
    logger.error(`创建食物时发生错误: ${error.message}`);
    throw new Error(`添加食物失败: ${error.message}`);
  }
};

/**
 * 获取所有食物分类列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Array>} 分类列表
 */
const getAllFoodCategories = async (options = {}) => {
  try {
    // 构建查询条件
    const filter = { isDeleted: false };
    
    // 如果指定了只获取活跃分类
    if (options.activeOnly) {
      filter.isActive = true;
    }
    
    // 获取未删除的分类
    const categories = await FoodCategory.find(filter)
      .sort({ order: 1, name: 1 }) // 优先按排序字段排序，然后按名称
      .lean()
      .exec();
    
    logger.info(`获取到${categories.length}个食物分类`);
    
    // 格式化分类数据
    const formattedCategories = categories.map(category => ({
      id: category._id,
      name: category.name,
      icon: category.image || '',
      description: category.description || '',
      order: category.order || 0,
      isActive: category.isActive !== false // 确保布尔值，默认为true
    }));

    return formattedCategories;
  } catch (error) {
    logger.error('获取食物分类失败:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, '获取食物分类失败');
  }
};

/**
 * 更新食物分类信息
 * @param {string} categoryId - 分类ID
 * @param {Object} updateData - 更新的数据
 * @returns {Promise<Object>} 更新后的分类对象
 */
const updateFoodCategory = async (categoryId, updateData) => {
  try {
    logger.info(`更新食物分类: ${categoryId}`);
    
    // 检查分类是否存在
    const category = await FoodCategory.findOne({ 
      _id: new mongoose.Types.ObjectId(categoryId),
      isDeleted: false 
    });
    
    if (!category) {
      logger.error(`分类不存在或已删除: ${categoryId}`);
      throw new ApiError(httpStatus.NOT_FOUND, '分类不存在或已删除');
    }
    
    // 更新分类
    const allowedFields = ['name', 'description', 'image', 'order', 'isActive'];
    const updateFields = {};
    
    allowedFields.forEach(field => {
      if (updateData[field] !== undefined) {
        updateFields[field] = updateData[field];
      }
    });
    
    // 特殊处理image字段，将API中的icon映射到数据库的image字段
    if (updateData.icon !== undefined) {
      updateFields.image = updateData.icon;
    }
    
    const updatedCategory = await FoodCategory.findByIdAndUpdate(
      categoryId,
      { $set: updateFields },
      { new: true }
    );
    
    logger.info(`分类更新成功: ${updatedCategory.name}`);
    
    return {
      id: updatedCategory._id,
      name: updatedCategory.name,
      icon: updatedCategory.image || '',
      description: updatedCategory.description || '',
      order: updatedCategory.order || 0,
      isActive: updatedCategory.isActive !== false
    };
  } catch (error) {
    logger.error(`更新食物分类失败: ${error.message}`);
    if (error.statusCode) {
      throw error;
    }
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `更新食物分类失败: ${error.message}`);
  }
};

/**
 * 删除食物分类(逻辑删除)
 * @param {string} categoryId - 分类ID
 * @returns {Promise<Object>} 结果对象
 */
const deleteFoodCategory = async (categoryId) => {
  try {
    logger.info(`删除食物分类: ${categoryId}`);
    
    // 检查分类是否存在
    const category = await FoodCategory.findOne({ 
      _id: new mongoose.Types.ObjectId(categoryId),
      isDeleted: false 
    });
    
    if (!category) {
      logger.error(`分类不存在或已删除: ${categoryId}`);
      throw new ApiError(httpStatus.NOT_FOUND, '分类不存在或已删除');
    }
    
    // 检查是否有食物使用此分类
    const foodCount = await Food.countDocuments({ 
      categoryId: new mongoose.Types.ObjectId(categoryId),
      isDeleted: false
    });
    
    if (foodCount > 0) {
      logger.warn(`无法删除分类，有${foodCount}个食物正在使用此分类`);
      throw new ApiError(httpStatus.BAD_REQUEST, `无法删除分类，有${foodCount}个食物正在使用此分类`);
    }
    
    // 执行逻辑删除
    const result = await FoodCategory.findByIdAndUpdate(
      categoryId,
      { $set: { isDeleted: true } },
      { new: true }
    );
    
    logger.info(`分类删除成功: ${result.name}`);
    
    return {
      id: result._id,
      name: result.name,
      deletedAt: new Date().toISOString()
    };
  } catch (error) {
    logger.error(`删除食物分类失败: ${error.message}`);
    if (error.statusCode) {
      throw error;
    }
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `删除食物分类失败: ${error.message}`);
  }
};

/**
 * 创建新的食物分类
 * @param {Object} categoryData - 分类数据
 * @returns {Promise<Object>} 创建的分类对象
 */
const createFoodCategory = async (categoryData) => {
  try {
    logger.info(`创建新的食物分类: ${categoryData.name}`);
    
    // 检查分类名称是否已存在
    const existingCategory = await FoodCategory.findOne({ 
      name: categoryData.name,
      isDeleted: false
    });
    
    if (existingCategory) {
      logger.warn(`分类名称已存在: ${categoryData.name}`);
      throw new ApiError(httpStatus.BAD_REQUEST, '分类名称已存在');
    }
    
    // 创建新的食物分类
    const category = new FoodCategory({
      name: categoryData.name,
      description: categoryData.description || '',
      image: categoryData.image || categoryData.icon || '',
      order: categoryData.order !== undefined ? categoryData.order : 0,
      isActive: categoryData.isActive !== undefined ? categoryData.isActive : true,
      isDeleted: false
    });
    
    // 保存到数据库
    const savedCategory = await category.save();
    logger.info(`食物分类创建成功: ${savedCategory.name}, ID: ${savedCategory._id}`);
    
    return {
      id: savedCategory._id,
      name: savedCategory.name,
      icon: savedCategory.image || '',
      description: savedCategory.description || '',
      order: savedCategory.order || 0,
      isActive: savedCategory.isActive !== false
    };
  } catch (error) {
    logger.error(`创建食物分类失败: ${error.message}`);
    if (error.statusCode) {
      throw error;
    }
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `创建食物分类失败: ${error.message}`);
  }
};

/**
 * 批量更新食物分类排序
 * @param {Array} categoriesOrder - 分类排序数组，包含id和order
 * @returns {Promise<Object>} 更新结果
 */
const updateCategoriesOrder = async (categoriesOrder) => {
  try {
    logger.info(`批量更新${categoriesOrder.length}个分类的排序`);
    
    const updatePromises = categoriesOrder.map(async (item) => {
      const { id, order } = item;
      return FoodCategory.updateOne(
        { _id: new mongoose.Types.ObjectId(id), isDeleted: false },
        { $set: { order } }
      );
    });
    
    // 并行执行所有更新
    const results = await Promise.all(updatePromises);
    
    // 计算成功更新的数量
    const updatedCount = results.reduce((count, result) => {
      return count + (result.modifiedCount || 0);
    }, 0);
    
    logger.info(`成功更新了${updatedCount}个分类的排序`);
    
    // 获取最新的分类列表
    const updatedCategories = await getAllFoodCategories();
    
    return {
      updatedCount,
      categories: updatedCategories
    };
  } catch (error) {
    logger.error(`更新分类排序失败: ${error.message}`);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `更新分类排序失败: ${error.message}`);
  }
};

/**
 * Delete food by ID
 * @param {ObjectId} foodId
 * @returns {Promise<Food>}
 */
const deleteFoodById = async (foodId) => {
  const food = await getFoodById(foodId); // Leverages existing function which throws ApiError if not found
  if (!food) {
    // This case should ideally be handled by getFoodById, but as a safeguard:
    throw new ApiError(httpStatus.NOT_FOUND, 'Food not found');
  }
  await food.remove(); // Or Food.findByIdAndDelete(foodId);
  return food; // Or return a success message/status
};

module.exports = {
  getFoods,
  getAllFoods,
  getFoodById,
  searchFoods,
  getOrCreateFoodCategory,
  createFood,
  getAllFoodCategories,
  updateFoodCategory,
  deleteFoodCategory,
  createFoodCategory,
  updateCategoriesOrder,
  deleteFoodById,
};